package server

import (
	"context"
	"fmt"
	"longmen/server/config/global"
	_const "longmen/server/pkg/common/helper/const"
	time2 "longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/protobuf"
	"math/rand"
	"time"
)

func (s *Server) GetNewsList(ctx context.Context, req *protobuf.GetNewsListReq) (*protobuf.GetNewsProfileListResp, error) {
	fName := "GetNewsList"
	newsList := make([]*models_main.News, 0)
	var err error
	global.Log.Debugf("GetNewsList req source:%v", req.GetSource())
	if req.GetNewsCategoryId() == 1 {
		newsList, err = db_main.GetNewsList(map[string]interface{}{"is_hot": 1, "status": 1}, int(req.GetPage()), int(req.GetSize()), req.GetSource())
		if err != nil {
			return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
		}
	} else if req.GetSiteCategoryId() == 100 {
		newsList, err = db_main.GetNewsList(map[string]interface{}{"status": 1}, int(req.GetPage()), int(req.GetSize()), req.GetSource())
		if err != nil {
			return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
		}
	} else if req.GetSiteCategoryId() > 0 {
		newsList, err = db_main.GetNewsList(map[string]interface{}{"category_site": req.GetSiteCategoryId(), "status": 1}, int(req.GetPage()), int(req.GetSize()), req.GetSource())
		if err != nil {
			return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
		}
	} else {
		newsList, err = db_main.GetNewsList(map[string]interface{}{"category_id": req.GetNewsCategoryId(), "status": 1}, int(req.GetPage()), int(req.GetSize()), req.GetSource())
		if err != nil {
			return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
		}
	}
	resp := make([]*protobuf.NewsProfile, 0)
	for _, news := range newsList {
		runes := []rune(util.TrimHtml(news.Content))
		i := 100
		if len(runes) < i {
			i = len(runes)
		}
		if req.GetSource() == _const.TERMINAL_PC {
			news.Img = news.Img + "?" + _const.ThumbCropUrl + _const.PCNewsListThumbSize
		} else {
			news.Img = news.Img + "?" + _const.ThumbCropUrl + _const.MobileListThumbSize
		}
		resp = append(resp, &protobuf.NewsProfile{
			Id:          uint32(news.ID),
			Title:       news.Title,
			Profile:     string(runes[0:i]) + "...",
			PublishTime: time.Unix(news.PublishTime, 0).Format(time2.TIME_LAYOUT_FORMAT_6),
			Img:         news.Img,
			Hits:        uint32(news.RandHits + news.Hits),
			AuthorName:  news.AuthorName,
		})
	}
	return &protobuf.GetNewsProfileListResp{NewsProfile: resp}, nil
}
func (s *Server) GetNewsCategoryList(ctx context.Context, empty *protobuf.Empty) (*protobuf.NewsCategoryResp, error) {
	fName := "GetNewsCategoryList"
	list, err := db_main.GetNewsCategoryList()
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	resp := make([]*protobuf.NewsCategory, 0)
	for _, category := range list {
		resp = append(resp, &protobuf.NewsCategory{
			Id:           int64(category.ID),
			CategoryName: category.CategoryName,
			Sort:         int64(category.Sort),
			Disabled:     int64(category.Disabled),
		})
	}
	return &protobuf.NewsCategoryResp{NewsCategory: resp}, err
}
func (s *Server) GetNewsById(ctx context.Context, req *protobuf.GetNewsByIdReq) (*protobuf.GetNewsByIdResp, error) {
	fName := "GetNewsByID"
	news, err := db_main.GetNewsById(int(req.Id))
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	getLastOrNextNewsList := make([]*protobuf.LastAndNext, 2)
	if news.IsHot != 1 {
		lastNews, err := db_main.GetLastNews(news.PublishTime, news.CategoryId)
		if err == nil {
			getLastOrNextNewsList[0] = &protobuf.LastAndNext{
				Id:    int64(lastNews.ID),
				Title: lastNews.Title,
			}
		}
		nextNews, err := db_main.GetNextNews(news.PublishTime, news.CategoryId)
		if err == nil {
			getLastOrNextNewsList[1] = &protobuf.LastAndNext{
				Id:    int64(nextNews.ID),
				Title: nextNews.Title,
			}
		}
	} else {
		lastNews, err := db_main.GetLastNewsByIsHot(news.PublishTime, news.IsHot)
		if err == nil {
			getLastOrNextNewsList[0] = &protobuf.LastAndNext{
				Id:    int64(lastNews.ID),
				Title: lastNews.Title,
			}
		}
		nextNews, err := db_main.GetNextNewsByIsHot(news.PublishTime, news.IsHot)
		if err == nil {
			getLastOrNextNewsList[1] = &protobuf.LastAndNext{
				Id:    int64(nextNews.ID),
				Title: nextNews.Title,
			}
		}
	}
	db_main.IncrNewHits(news)
	resp := &protobuf.GetNewsByIdResp{
		Title:      news.Title,
		Content:    news.Content,
		AuthorName: news.AuthorName,
		Status:     int32(news.Status),
		//PublishTime: timehelper.Unix(news.PublishTime-8*60*60, 0).Format(util.TIME_LAYOUT_FORMAT_6),
		PublishTime: time.Unix(news.PublishTime, 0).Format(time2.TIME_LAYOUT_FORMAT_6),
		Img:         global.Config.GetString("news.img_url") + news.Img,
		LastAndNext: getLastOrNextNewsList,
		Hits:        int64(news.RandHits + news.Hits + 1),
	}
	return resp, nil
}
func (s *Server) GetNewsBannerList(ctx context.Context, req *protobuf.GetBannerReq) (*protobuf.GetBannerResp, error) {
	fName := "GetNewsBannerList"
	var err error
	//if req.Device == 1 {
	//	newsList, err = db_main.GetBannerList()
	//} else {
	//	newsList, err = db_main.GetNewsList(map[string]interface{}{"is_banner": 2, "status": 1}, 1, 6, 0)
	//}

	newsBannerList, err := db_main.GetBannerList()

	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	resp := make([]*protobuf.Banner, 0)
	for _, news := range newsBannerList {
		newsContent := ""
		runeStr := []rune(util.TrimHtml(news.Content))
		if len(runeStr) > 50 {
			newsContent = string(runeStr[:50]) + "..."
		}
		if req.GetDevice() == _const.TERMINAL_PC {
			news.Img = news.Img + "?" + _const.ThumbCropUrl + _const.PCNewsBannerSize
		} else {
			news.Img = news.Img + "?" + _const.ThumbCropUrl + _const.MobileBannerSize
		}
		resp = append(resp, &protobuf.Banner{
			Id:      int64(news.ID),
			Title:   news.Title,
			Img:     news.Img,
			Content: newsContent,
		})
	}
	return &protobuf.GetBannerResp{
		Banner: resp,
	}, nil
}
func (s *Server) GetRecommendNewsList(ctx context.Context, empty *protobuf.Empty) (*protobuf.GetNewsProfileListResp, error) {
	fName := "GetRecommendNewsList"
	rsLimit := 3
	newsList, err := db_main.GetNewsList(map[string]interface{}{"is_hot": 1}, 1, 30, 0)
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	var newListRand []*models_main.News
	if len(newsList) > 10 {
		skip := make(map[int]int)
		for len(skip) < 3 {
			rand.Seed(time.Now().UnixNano())
			local := rand.Intn(len(newsList) - 1)
			if _, ok := skip[local]; !ok {
				newListRand = append(newListRand, newsList[local])
				skip[local] = local
			}
		}
	} else {
		newListRand = newsList
	}

	resp := make([]*protobuf.NewsProfile, 0)
	for i, news := range newListRand {
		if i >= rsLimit {
			break
		}
		runes := []rune(util.TrimHtml(news.Content))
		lenRunes := 50
		if len(runes) < 50 {
			lenRunes = len(runes)
		}
		resp = append(resp, &protobuf.NewsProfile{
			Id:          uint32(news.ID),
			Title:       news.Title,
			Profile:     string(runes[0:lenRunes]),
			PublishTime: time.Unix(news.PublishTime-8*60*60, 0).Format(time2.TIME_LAYOUT_FORMAT_6),
			//Img:         global.Config.GetString("news.img_url") + news.Img,
			Img: news.Img,
		})
	}
	return &protobuf.GetNewsProfileListResp{
		NewsProfile: resp,
	}, err
}
